package com.herui.ota.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.Collator;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

/**
 * 根据IP地址获取详细的地域信息
 */
@Slf4j
public class AddressUtils {

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();
        return ipAddress;
    }

    public static String getAreaByIp(String ip){

        String url = "https://api.ipplus360.com/ip/geo/v1/city/?" +
                "key=kUy7O7eL3xB7KOqJ0dGdvi50D35PWtTm0qrRiDwo1Nmfb5fXMP5brE6fDMzL9fBC" +
                "&ip=" +ip+
                "&coordsys=WGS84";

        String s = HttpUtil.get(url);
        log.info("地址查询:{}", s);

        JSONObject jsonObject = JSON.parseObject(s);
        String code = jsonObject.getString("code");
        if (code.equals("Success")){
            JSONObject data = jsonObject.getJSONObject("data");
            String country = data.getString("country");
            if (StringUtils.isEmpty(country)){
                return "未知";
            }
            return country;
        }
        return "未知";
    }

    public static String getFirstLetter(String chinese) {
        StringBuilder sb = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            String[] pinyin = Collator.getInstance(Locale.CHINESE).getCollationKey(String.valueOf(c)).toString().split(" ");
            for (String s : pinyin) {
                if (s.length() > 0) {
                    sb.append(Character.toUpperCase(s.charAt(0)));
                    break;
                }
            }
        }
        return sb.toString();
    }

    public static String getPinYinFirst(String chinese) {
        StringBuilder str = new StringBuilder();
        // 遍历字符串
        for (int i = 0; i < chinese.length(); i++) {
            char c = chinese.charAt(i);
            // 非中文字符直接拼接到结果字符串
            if (!isChinese(c)) {
                str.append(c);
            } else {
                // 中文字符获取其拼音首字母，并拼接到结果字符串
                str.append(getFirstPinYin(c));
            }
        }
        return str.toString().toUpperCase();
    }
    // 判断是否为中文字符
    public static boolean isChinese(char c) {
        return (c >= 0x4E00 && c <= 0x9FFF);
    }
    // 获取中文字符的拼音首字母
    public static char getFirstPinYin(char c) {
        if (isChinese(c)) {
            String pinyin = String.valueOf(c);
            return pinyin.charAt(0);
        }
        return c;
    }

    public static void main(String[] args) {
        getAreaByIp("125.116.184.131");
    }
}
